/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import DTO.album.Albums;
import DTO.playlist.Playlists;
import DTO.song.Songs;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import xmlutils.SearchAlbumSAXHandler;
import xmlutils.SearchPlaylistSAXHandler;
import xmlutils.SearchSongSAXHandler;

/**
 *
 * @author NoiR
 */
public class AjaxMusicPlayerServlet extends HttpServlet {

    private final String albumxml = "xml/Albums.xml";
    private final String songxml = "xml/Songs.xml";
    private final String playlistxml = "xml/Playlists.xml";
    private Albums albums;
    private Songs songs;
    private Playlists playlists;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String id = request.getParameter("id");
            String type = request.getParameter("type");
            String realPath = getServletContext().getRealPath("/");


            // process, 1 - song, 2 - album, 3 - playlist, 4 - mv
            if ("1".equals(type) || "4".equals(type)) {
                String filePath = realPath + songxml;
                SAXParserFactory spf = SAXParserFactory.newInstance();
                SAXParser sax = spf.newSAXParser();
                SearchSongSAXHandler objHandler = new SearchSongSAXHandler(id);

                File file = new File(filePath);
                sax.parse(file, objHandler);

                songs = objHandler.getSongs();

                if (songs != null) {
                    JAXBContext ctx = JAXBContext.newInstance(songs.getClass());
                    Marshaller mar = ctx.createMarshaller();
                    mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
                    mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                    response.setContentType("text/xml");
                    response.setCharacterEncoding("UTF-8");
                    mar.marshal(songs, out);
                }
            } else if ("2".equals(type)) {
                String filePath = realPath + albumxml;
                SAXParserFactory spf = SAXParserFactory.newInstance();
                SAXParser sax = spf.newSAXParser();
                SearchAlbumSAXHandler objHandler = new SearchAlbumSAXHandler(id);

                File file = new File(filePath);
                sax.parse(file, objHandler);

                albums = objHandler.getAlbums();

                if (albums != null) {
                    JAXBContext ctx = JAXBContext.newInstance(albums.getClass());
                    Marshaller mar = ctx.createMarshaller();
                    mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
                    mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                    response.setContentType("text/xml");
                    response.setCharacterEncoding("UTF-8");
                    mar.marshal(albums, out);
                }
            } else if ("3".equals(type)) {
                String filePath = realPath + playlistxml;
                SAXParserFactory spf = SAXParserFactory.newInstance();
                SAXParser sax = spf.newSAXParser();
                SearchPlaylistSAXHandler objHandler = new SearchPlaylistSAXHandler(id);

                File file = new File(filePath);
                sax.parse(file, objHandler);

                playlists = objHandler.getPlaylist();

                if (playlists != null) {
                    JAXBContext ctx = JAXBContext.newInstance(playlists.getClass());
                    Marshaller mar = ctx.createMarshaller();
                    mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
                    mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                    response.setContentType("text/xml");
                    response.setCharacterEncoding("UTF-8");
                    mar.marshal(playlists, out);
                }
            } // end song and mv
        } catch (JAXBException ex) {
            Logger.getLogger(AjaxMusicPlayerServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(AjaxMusicPlayerServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(AjaxMusicPlayerServlet.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
